package net.wicp.tams.common.connector.executor.busi;

import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.Properties;

import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.connector.config.AbstractConfigClass;
import net.wicp.tams.common.connector.config.xmlParser.ConfigClassXml;
import net.wicp.tams.common.connector.executor.impl.AbsConfigManager;
import net.wicp.tams.common.exception.ProjectException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 * 需要在根路径下存在 service.properties 服务配置文件
 * 
 * @author zhoujunhui
 *
 */
public class FileConfigManager extends AbsConfigManager {
	public static final Properties serviceProp = new Properties();
	private final static Logger logger = LoggerFactory.getLogger(FileConfigManager.class);

	public FileConfigManager(String dir) {
		super(dir);
	}

	public FileConfigManager() {
		super();
	}

	static {
		try {
			URL jarurl = Thread.currentThread().getContextClassLoader().getResource("/service.properties");// 绝对路径
			if (jarurl == null) {
				jarurl = Thread.currentThread().getContextClassLoader().getResource("service.properties");
			}
			String url = jarurl.getPath();
			serviceProp.load(new FileReader(new File(url)));
		} catch (Exception e) {
			logger.error("------没有获得服务定义文件service.properties------", e);
		}
	}

	@Override
	protected AbstractConfigClass createConfig(String appKey) {
		String xmlValue = FileConfigManager.serviceProp.getProperty(String.format("%s.%s", appKey, "xml"));
		try {
			String path = StringUtil.isNull(dir) ? xmlValue : IOUtil.mergeFolderAndFilePath(dir, xmlValue);
			AbstractConfigClass retobj = ConfigClassXml.createConfigClassXml(appKey,
					IOUtil.fileToInputStream(path, null));
			return retobj;
		} catch (ProjectException e) {
			logger.error("------加载" + appKey + "对应的xml错误------", e);
			throw new IllegalArgumentException("------加载" + appKey + "对应的xml错误------");
		}
	}

}
